1
2
3
4 package joeq.Scheduler;
5
6 import java.util.Iterator;
7 import jwutil.util.Assert;
8
9
10
11
12
13 public class jq_ThreadQueue {
14
15 private jq_Thread head, tail;
16 private int size;
17
18 public boolean isEmpty() {
19 return head == null;
20 }
21
22 public void enqueue(jq_Thread t) {
23 Assert._assert(t.next == null);
24 if (head == null) head = t;
25 else tail.next = t;
26 tail = t;
27 ++size;
28 }
29
30 public void enqueueFront(jq_Thread t) {
31 Assert._assert(t.next == null);
32 if (head == null) tail = t;
33 else head.next = t;
34 head = t;
35 ++size;
36 }
37
38 public jq_Thread dequeue() {
39 jq_Thread t = head;
40 if (t == null) return null;
41 head = t.next;
42 t.next = null;
43 if (head == null) tail = null;
44 --size;
45 return t;
46 }
47
48 public jq_Thread peek() {
49 return head;
50 }
51
52 public int length() {
53 return size;
54 }
55
56 public void verifyLength() {
57 jq_Thread p = head;
58 int i = 0;
59 while (p != null) {
60 p = p.next;
61 ++i;
62 }
63 Assert._assert(size == i);
64 }
65
66 public boolean remove(jq_Thread t2) {
67 jq_Thread p = head, q = null;
68 while (p != t2) {
69 if (p == null) return false;
70 q = p;
71 p = p.next;
72 }
73 if (q == null) {
74 Assert._assert(head == t2);
75 head = t2.next;
76 if (head == null) tail = null;
77 else t2.next = null;
78 } else {
79 q.next = p.next;
80 if (p.next == null) {
81 Assert._assert(p == tail);
82 tail = q;
83 } else {
84 p.next = null;
85 }
86 }
87 --size;
88 return true;
89 }
90
91 public Iterator threads() {
92 final jq_Thread start = head;
93 return new Iterator() {
94 jq_Thread t = start;
95 public boolean hasNext() {
96 return t != null;
97 }
98 public Object next() {
99 jq_Thread t2 = t;
100 t = t.next;
101 return t2;
102 }
103 public void remove() { throw new UnsupportedOperationException(); }
104 };
105 }
106
107 public String toString() {
108 StringBuffer s = new StringBuffer("{ ");
109 Iterator i = threads();
110 if (i.hasNext()) {
111 s.append(i.next().toString());
112 while (i.hasNext()) {
113 s.append(", ");
114 s.append(i.next().toString());
115 }
116 }
117 s.append(" }");
118 return s.toString();
119 }
120
121 }